﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.API.Write.Application.Command.PhysicalGrid;
using SC.GridManage.Domain.Models;

namespace SC.GridManage.API.Write.Application.Handler.PhysicalGrid
{
    public class DelPhysicalGridHandler : IRequestHandler<DelPhysicalCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<PhysicalGridModel> physicalGridRepo;
        private readonly ILogger<CreatePhysicalHandler> logger;
        private readonly IMapper mapper;

        public DelPhysicalGridHandler(IBaseRepository<PhysicalGridModel> physicalGridRepo,
            ILogger<CreatePhysicalHandler> logger,
            IMapper mapper)
        {
            this.physicalGridRepo = physicalGridRepo;
            this.logger = logger;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(DelPhysicalCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var model = physicalGridRepo.GetModelAsync(request.Id).Result;
            if (model != null)
            {
                model.IsDeleted = true;

              int r =  physicalGridRepo.UpdateAsync(model).Result;

                if (r > 0)//判断受影响的行数是否大于0
                {
                    result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
                    result.Msg = "删除成功.";
                    result.Data = r;
                }
                else
                {
                    result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                    result.Msg = "删除失败.";
                }

            }
            else {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Error;
                result.Msg = "您要删除的数据不存在!";
            }

            //把 公共响应类result 返回给控制器(调用方)
            return Task.FromResult(result);
        }
    }
}
